import React, {useContext, useEffect, useMemo, useRef, useState} from 'react'
// import type { InputRef } from 'antd';
import {Button, Form, InputNumber, Popconfirm, Table, message} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import type {FormInstance} from 'antd/es/form'
import Styles from './index.less'

const EditableContext = React.createContext<FormInstance<any> | null>(null)

// eslint-disable-next-line react/function-component-definition
const EditableRow: any = (props: any) => {
	const {pageType, list, forms, setForms} = props
	// eslint-disable-next-line react/destructuring-assignment
	const num = Number(props['data-row-key'])
	const [form] = Form.useForm()
	if (!forms[num - 1]) {
		const newF = forms
		newF.push(form)
		setForms(newF)
	}
	return (
		<Form
			form={form}
			component={false}
			layout="vertical"
			initialValues={list[num - 1]}
			disabled={pageType === 'detail' || pageType === 'audit'}>
			<EditableContext.Provider value={form}>
				<tr {...props} />
			</EditableContext.Provider>
		</Form>
	)
}

// eslint-disable-next-line react/function-component-definition
const EditableCell: React.FC<any> = ({
	title,
	editable,
	children,
	dataIndex,
	record,
	num,
	handleSave,
	list,
	idx,
	...restProps
}) => {
	const inputRef = useRef<any>(null)
	const form = useContext(EditableContext)!

	const index = useMemo(() => {
		if (record?.correspondingLadder) {
			return Number(record.correspondingLadder)
		}
		return 0
	}, [record])

	const save = async () => {
		try {
			const values = await form.validateFields()
			// toggleEdit();
			handleSave({...record, ...values})
		} catch (errInfo) {
			/* empty */
		}
	}
	let childNode = children

	let text = ''
	let tip = ''
	if (num === 1) {
		if (title === 'number') {
			text = `阶梯${index}上限数量`
			tip = '阶梯上限数量应大于前一个阶梯上限数量'
		}
		if (title === 'amount') {
			text = `阶梯${index}奖励金额/单`
		}
		if (title === 'ladderBd') {
			text = `阶梯${index}BD跟单费/单`
		}
	}

	if (num === 2) {
		if (title === 'number') {
			text = `阶梯${index}下限数量`
			tip = '阶梯下限数量应大于前一个阶梯下限数量'
		}
		if (title === 'amount') {
			text = `阶梯${index}奖励金额`
		}
	}
	// let minNumber: number = 0
	// if (list?.length) {
	// 	const newList = [...list]
	// 	newList?.splice(idx)
	// 	const maxData: any = newList?.sort(
	// 		(a: {number: number}, b: {number: number}) => b.number - a.number,
	// 	)[0]
	// 	if (maxData?.number) {
	// 		minNumber = Number(maxData?.number) + 1
	// 	}
	// }

	const rulesData: any = [
		{
			required: true,
			message: `必填项`,
		},
	]
	if (dataIndex === 'number') {
		rulesData.push({
			pattern: /^[0-9]*$/,
			message: '只可以输入整数',
		})
	}
	if (editable) {
		childNode = (
			<Form.Item
				style={{margin: 0}}
				name={dataIndex}
				label={text}
				rules={rulesData}
				tooltip={dataIndex === 'number' ? tip : ''}>
				<InputNumber
					ref={inputRef}
					defaultValue={record[dataIndex]}
					onPressEnter={save}
					onBlur={save}
					// onChange={save}
				/>
			</Form.Item>
		)
	}

	return <td {...restProps}>{childNode}</td>
}

type EditableTableProps = Parameters<typeof Table>[0]

// interface DataType {
//   key: React.Key;
//   name: string;
//   age: string;
//   address: string;
// }

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>

// eslint-disable-next-line react/function-component-definition
const App: any = (props: any) => {
	const {
		edType = 1,
		num,
		list = [],
		setList,
		andAmount,
		forms,
		setForms,
		pageType,
	} = props
	const Et = useMemo(() => [4, 5].includes(edType), [edType])

	// const [list, setList] = useState<any[]>([]);

	// useEffect(()=>{
	//   setList(list)
	// },[list])

	const [count, setCount] = useState(2)
	const handleDelete = (correspondingLadder: any) => {
		if (andAmount) {
			message.error('阶梯奖励和冲单奖励必须至少存在一条')
		} else {
			const newData = list.filter(
				(item: any) => item.correspondingLadder !== correspondingLadder,
			)
			setList(newData)
			if (forms[Number(correspondingLadder) - 1]) {
				const newF = [...forms]
				newF.pop()
				setForms(newF)
			}
		}
	}

	const handleAdd = () => {
		const newData: any = Et
			? {
					correspondingLadder: (list.length + 1).toString(),
					number: '',
					amount: '',
					ladderBd: '',
			  }
			: {
					correspondingLadder: (list.length + 1).toString(),
					number: '',
					amount: '',
			  }
		setList([...list, newData])
		setCount(count + 1)
	}

	const defaultColumns: any[] = Et
		? [
				{
					title: 'number',
					dataIndex: 'number',
					width: '200px',
					editable: true,
				},
				{
					title: 'amount',
					dataIndex: 'amount',
					width: '200px',
					editable: true,
				},
				{
					title: 'ladderBd',
					dataIndex: 'ladderBd',
					width: '200px',
					editable: true,
				},
				{
					title: 'operation',
					dataIndex: 'operation',
					render: (_: any, record: any, index: any) =>
						list.length === index + 1
							? [
									<Popconfirm
										title="确定要删除吗?"
										onConfirm={() =>
											handleDelete(
												record.correspondingLadder,
											)
										}>
										<Button
											type="link"
											disabled={
												pageType === 'detail' ||
												pageType === 'audit'
											}>
											删除
										</Button>
									</Popconfirm>,
									<Button
										type="link"
										onClick={handleAdd}
										disabled={
											pageType === 'detail' ||
											pageType === 'audit'
										}>
										添加
									</Button>,
							  ]
							: null,
				},
		  ]
		: [
				{
					title: 'number',
					dataIndex: 'number',
					width: '200px',
					editable: true,
				},
				{
					title: 'amount',
					dataIndex: 'amount',
					width: '200px',
					editable: true,
				},
				{
					title: 'operation',
					dataIndex: 'operation',
					render: (_: any, record: any, index: any) =>
						list.length === index + 1
							? [
									<Popconfirm
										title="确定要删除吗?"
										onConfirm={() =>
											handleDelete(
												record.correspondingLadder,
											)
										}>
										<Button
											type="link"
											disabled={
												pageType === 'detail' ||
												pageType === 'audit'
											}>
											删除
										</Button>
									</Popconfirm>,
									<Button
										type="link"
										onClick={handleAdd}
										disabled={
											pageType === 'detail' ||
											pageType === 'audit'
										}>
										添加
									</Button>,
							  ]
							: null,
				},
		  ]

	useEffect(() => {
		setList(list)
	}, [list])

	const handleSave = (row: any) => {
		const newData = [...list]
		const index = newData.findIndex(
			(item) => row.correspondingLadder === item.correspondingLadder,
		)
		const item = newData[index]
		newData.splice(index, 1, {
			...item,
			...row,
		})
		setList(newData)
	}

	const components = {
		body: {
			row: (prop: any) => EditableRow({...props, ...prop}),
			cell: EditableCell,
		},
	}

	const columns = defaultColumns.map((col) => {
		if (!col.editable) {
			return col
		}
		return {
			...col,
			onCell: (record: any, idx: any) => ({
				record,
				editable: col.editable,
				dataIndex: col.dataIndex,
				title: col.title,
				num,
				handleSave,
				list,
				idx,
			}),
		}
	})

	return (
		<div className={Styles.basics}>
			<div className={Styles.titleBox}>
				{num === 1 ? '阶梯奖励' : '冲单奖励'}
			</div>
			<div className={Styles.formBox}>
				{list.length > 0 ? (
					<Table
						showHeader={false}
						style={{width: '900px', margin: '0 auto'}}
						components={components}
						rowKey={(record: any) => record.correspondingLadder}
						rowClassName={() => 'editable-row'}
						bordered
						pagination={false}
						dataSource={list}
						columns={columns as ColumnTypes}
					/>
				) : (
					<Button
						icon={<PlusOutlined />}
						type="primary"
						ghost
						size="small"
						onClick={handleAdd}
						disabled={
							pageType === 'detail' || pageType === 'audit'
						}>
						新增
					</Button>
				)}
			</div>
		</div>
	)
}

export default App
